package org.gp953.org.service.impl;

import org.gp953.basic.service.impl.BaseServiceImpl;
import org.gp953.basic.util.PageList;
import org.gp953.org.domain.Department;
import org.gp953.org.mapper.DepartmentMapper;
import org.gp953.org.query.DepartmentQuery;
import org.gp953.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.save(department);
        /*Long id = department.getParent().getId();
        String dirPath = departmentMapper.loadById(id).getDirPath();
        dirPath = dirPath + "/" + department.getId();
        department.setParent_id(id);
        department.setDirPath(dirPath);
        departmentMapper.update(department);*/
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        // 获取该对象的parent_id
        Long pid = department.getParent().getId();

        String dirPath = "";
        if (pid != null){// 通过pid是否为空来判断是不是顶级部门
            if(pid == department.getId()){// 通过判断当前对象的id和他的父级id是否相等来解决：
                // 编辑时选自己为上级部门，会使dirPath层级无限叠加的bug，即选自己为上级部门时不修改dir只修改其他数据。
                departmentMapper.update(department);
                return;// 直接结束方法,不继续执行
            }
            // 通过该对象的parent_id去查询父级的部门的dirpath
            dirPath = departmentMapper.loadById(pid).getDirPath();
        }
        // 通过id去拼接现在的dirpath
        dirPath = dirPath + "/" + department.getId();
        // 从新设置parent_id和dirpath后保存
        department.setParent_id(pid);
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> queryTree() {
        return departmentMapper.loadTree();
    }
}
